package com.desaysv.hicar

import android.annotation.SuppressLint
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONObject
import com.desaysv.hicar.IProxy.ProxyFactory
import com.desaysv.hicar.IProxy.proxy.impl.Proxy1
import com.desaysv.hicar.IProxy.proxy.impl.Proxy2
import com.desaysv.hicar.IProxy.proxy.impl.Proxy3
import com.desaysv.hicar.IProxy.proxy.impl.Proxy4
import com.desaysv.hicar.http.*
import com.desaysv.someip.SomeIpManager
import com.desaysv.someip.SomeIpMessager
import com.desaysv.svhttp.SVHttp
import com.desaysv.svhttp.callback.IRequestCallBack
import com.desaysv.svhttp.utils.SVUtils
import com.desaysv.svview.adapter.BaseRecycleAdapter
import java.text.SimpleDateFormat


class MainActivity : AppCompatActivity() {
    //    @RequiresApi(Build.VERSION_CODES.N)
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        val tvLogs = findViewById<TextView>(R.id.tvLogs)
//        val tvSetting = findViewById<TextView>(R.id.tvSetting)
//        var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//
//        ProxyFactory.getFactory().getProxy(Proxy1::class.java)
//        ProxyFactory.getFactory().getProxy(Proxy2::class.java)
//        ProxyFactory.getFactory().getProxy(Proxy3::class.java)
//        ProxyFactory.getFactory().getProxy(Proxy4::class.java)
//
//        ProxyFactory.getFactory().getProxy(Proxy1::class.java).print()
//        ProxyFactory.getFactory().getProxy(Proxy2::class.java).print2()
//        ProxyFactory.getFactory().getProxy(Proxy3::class.java).print3()
//        ProxyFactory.getFactory().getProxy(Proxy4::class.java).print4()
//
////        try {
////            var pro1=Proxy1()
////            pro1.print()
////        } catch (e: Exception) {
////            e.printStackTrace()
////        }
//        tvLogs?.setOnClickListener {
//            doAction(tvLogs)
//        }
//        doAction(tvLogs)
//
////        checkPermission()
//
//
//        var builder = SomeIpMessager.Buidler(6)
//            .setMethodId(0x02)
//            .setClientId(0x02)
//        var info = builder.builder("1234", true)
//        Log.e(TAG, "onCreate: " + SomeIpMessager.byteArrayToHexString(info))
//        var msg = SomeIpMessager.decoder(info, true)
//        Log.e(TAG, "onCreate: " + msg)
//        Log.e(TAG, "onCreate: " + String(msg.payload))
//
//        SomeIpManager.getInstance().addObserver(object : SomeIpManager.SomeIpObserverImpl() {
//            override fun response(messager: SomeIpMessager?) {
//                Log.e(TAG, "response: " + messager?.methodId)
//                Log.e(TAG, "response: " + messager?.messageType)
//            }
//
//            override fun timeout(methodId: Int, sessionId: Int) {
//                Log.e(TAG, "timeout: methodId=>${methodId}超时，当前sessionId:${sessionId}")
//            }
//
//        })
//        SomeIpManager.getInstance().send(0x11, "1234".toByteArray())
//        SomeIpManager.getInstance().send(0x10, byteArrayOf(0x01, 0x02, 0x03, 0x0f))
////        val intent = Intent()
////        intent.action = "com.desaysv.someip"
////        intent.setPackage("com.desaysv.hicar")
////        val bind=bindService(intent, mConnection, BIND_AUTO_CREATE)
////        Log.e(TAG, "onCreate: "+bind )
//        var options = ActivityOptions.makeBasic()
//
////        tvSetting.setOnClickListener {
////            setAlarm()
////        }
//
//        setAdapetr()

        window.decorView.postDelayed({
//            val intent = Intent()
//            //自定义的条件用来跳到自己写的页面内部的app页面跳转
//            intent.setAction(Intent.ACTION_VIEW)
//            intent.setData(Uri.parse("deeplink://toyota.huawei.desaysv/restmode?appId=com.huawei.intelligentcar&appName=xxx"))
//            startActivity(intent)

             var intent=Intent(this@MainActivity,MainActivity2::class.java)
            startActivity(intent)

        },5000)
    }
    
    private fun setAdapetr() {
        val recyclerView = findViewById<RecyclerView>(R.id.recycle)
        val adapter = object : BaseRecycleAdapter() {
            override fun setContext(): Context {
                return this@MainActivity
            }

            override fun setView(): Int {
                return R.layout.item_layout
            }

            override fun setSize(): Int {
                return 10
            }

            override fun bind(item: HolderProxy?, position: Int) {
                if (position == 0) {
                    item?.let {
                        it.itemView.scaleX = 1.0f
                        it.itemView.scaleY = 1.0f
                    }
                }else{
                    item?.let {
                        it.itemView.scaleX = 0.8f
                        it.itemView.scaleY = 0.8f
                    }
                }
            }
        }
        recyclerView.layoutManager = ActiveLinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        recyclerView.adapter = adapter
    }


    fun setAlarm() {
//        // 打开系统铃声设置
//        val intent = Intent(
//            RingtoneManager.ACTION_RINGTONE_PICKER
//        )
//        // 类型为来电RINGTONE
//        intent.putExtra(
//            RingtoneManager.EXTRA_RINGTONE_TYPE,
//            RingtoneManager.TYPE_RINGTONE
//        )
//        // 设置显示的title
//        intent.putExtra(
//            RingtoneManager.EXTRA_RINGTONE_TITLE,
//            "linzi设置来电铃声"
//        )
//        // 当设置完毕之后返回到当前的Activity
//        startActivityForResult(intent, 10002)
        // 打开系统铃声设置
        // 打开系统铃声设置
        val intent = Intent(
            RingtoneManager.ACTION_RINGTONE_PICKER
        )
        // 设置铃声类型和title
        // 设置铃声类型和title
        intent.putExtra(
            RingtoneManager.EXTRA_RINGTONE_TYPE,
            RingtoneManager.TYPE_NOTIFICATION
        )
        intent.putExtra(
            RingtoneManager.EXTRA_RINGTONE_TITLE,
            "林子设置通知铃声"
        )
        // 当设置完毕之后返回到当前的Activity
        // 当设置完毕之后返回到当前的Activity
        startActivityForResult(intent, 10002)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 10002 && resultCode == RESULT_OK) {
            // 得到我们选择的铃声
            val pickedUri: Uri? =
                data?.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
            RingtoneManager.setActualDefaultRingtoneUri(
                this,
//                RingtoneManager.TYPE_RINGTONE, pickedUri)
                RingtoneManager.TYPE_NOTIFICATION, pickedUri
            )
        }
    }

//    private var mSomeIpService:ISomeIpService?=null
//    private val mSomeIpCallback = object :ISomeIpCallback.Stub(){
//        override fun response(messager: SomeIpMessager?) {
//            Log.e(TAG, "response: " )
//        }
//
//        override fun timeout(methodId: Int, sessionId: Int) {
//            Log.e(TAG, "timeout: methodId=>${methodId}超时，当前sessionId:${sessionId}" )
//        }
//
//    }
//    private val mConnection=object :ServiceConnection{
//        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//            mSomeIpService = ISomeIpService.Stub.asInterface(service)
//            mSomeIpService?.register(mSomeIpCallback)
//
//            mSomeIpService?.send(0x11, "1234".toByteArray())
//            mSomeIpService?.send(0x10, byteArrayOf(0x01,0x02,0x03,0x0f))
//        }
//
//        override fun onServiceDisconnected(name: ComponentName?) {
//            mSomeIpService=null
//        }
//    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "onDestroy: ")
        SomeIpManager.getInstance().destroy()
//        unbindService(mConnection)
    }

    fun doAction(tvLogs: TextView?) {
//        10.219.114.197:9091/hozonGame/buryPointCollect/v1/collectPlatformBuryPoints
        var json = "{\n" +
                "    \"startTime\": \"2023-02-02 01:00:00\",\n" +
                "    \"endTime\": \"2023-02-02 19:00:00\",\n" +
                "    \"accessToken\": \"testAccessToken\"\n" +
                "}"
        var json2 = """
            {
                "name":"你好啊",
                "age":12,
                "date":"2023-02-23"
            }
        """.trimIndent().trim()
        var entity = VoEntity()
        entity.startTime = "2023-02-02 01:00:00"
        entity.endTime = "2023-02-02 19:00:00"
        entity.accessToken = "testAccessToken"
        //调用测试
        SVHttp.Builder()
//            .setHttpProxy(TestHandler::class.java)
            .setBaseUrl("http://47.108.85.176:80")
//            .setBaseUrl("https://linziblog.cn")
//            .setBaseUrl("http://10.219.114.197:9091")
//            .setResponseCoder(object :IResponseDecoder{
//                override fun <T : Any?> decoder(response: ByteArray?, t: Class<T>?): T {
//                    Log.d(getTag(),String(response!!))
//                    return JSONObject.parseObject(response,t)
//                }
//
//                override fun <T : Any?> decoder(response: ByteArray?, t: Type?): T {
//                    return JSONObject.parseObject(response,t)
//                }
//            })
            .setInterceptor(TestInterceptor())
            .setInterceptor(TestInterceptor2())
            .build()
            .create(Test::class.java)
//            .test3("2023-02-02 01:00:00","2023-02-02 19:00:00","testAccessToken",object :IRequestCallBack<Any?>{
//            .test4(json,object :IRequestCallBack<TestEntity?>{
//                override fun start() {
//                }
//
//                override fun error(error: Throwable?) {
//                    Log.e(TAG, "error: ",error )
//                }
//
//                override fun complete() {
//                }
//
//                override fun response(
//                    status: Int,
//                    headers: MutableMap<String, MutableList<String>>?,
//                    t: TestEntity?
//                ) {
//                }
//
//            })
//            .test("大家好","wo hen hao",object :IRequestCallBack<String>{
            .test2("17323170819", SVUtils.getMd5("123456"), object : IRequestCallBack<TestEntity> {
                override fun start() {
                    Log.d(getTag(), "开始")
                    tvLogs?.text = "${tvLogs?.text}\n开始"
                }

                override fun error(error: Throwable?) {
                    Log.d(getTag(), error!!.message!!)
                    tvLogs?.text = "${tvLogs?.text}\n错误"
                }

                @SuppressLint("SetTextI18n")
                override fun response(
                    status: Int,
                    headers: MutableMap<String, MutableList<String>>?,
                    t: TestEntity?
                ) {
                    t?.apply {
                        tvLogs?.text = "${tvLogs?.text}\n成功:${status}"
                        tvLogs?.text = "${tvLogs?.text}\n成功:${code}"
                        tvLogs?.text = "${tvLogs?.text}\n成功:${msg}"
                        tvLogs?.text = "${tvLogs?.text}\n成功:${JSONObject.toJSONString(headers)}"
                    }

                }

                @SuppressLint("SetTextI18n")
                override fun complete() {
                    Log.d(getTag(), "完成")
                    tvLogs?.text = "${tvLogs?.text}\n完成"
                }

//                override fun response(
//                    status: Int,
//                    headers: MutableMap<String, MutableList<String>>?,
//                    t: String?
//                ) {
//                    t?.apply {
//                        tvLogs?.text="${tvLogs?.text}\n成功:${status}"
//                        tvLogs?.text="${tvLogs?.text}\n成功:${JSONObject.toJSONString(headers)}"
//                    }
//                }

            })
//            .down("http://img.linziblog.cn/1634785119614bfdd31d9-5a5e-4fed-933b-1b3a8c43b823.png",MainActivity@this.cacheDir.absolutePath+"/111123456.png",object :
//                IDownLoadCallBack {
//                override fun start() {
//                    Log.d(getTag(),"开始")
//                    tvLogs?.text="${tvLogs?.text}\n开始"
//                }
//
//                override fun error(error: Throwable?) {
//                    Log.d(getTag(),error!!.message!!)
//                    tvLogs?.text="${tvLogs?.text}\n错误"
//                }
//
//                override fun complete() {
//                    Log.d(getTag(),"完成")
//                    tvLogs?.text="${tvLogs?.text}\n完成"
//                }
//
//                override fun response(status: Int, t: File?) {
//                    tvLogs?.text="${tvLogs?.text}\n完成存放：${t?.exists()}"
//                }
//
//                override fun progress(size: Long, total: Long) {
//                    tvLogs?.text="${tvLogs?.text}\n进度：${size}/${total}"
//                }
//
//            })
    }

    private val TAG = "MainActivity"
//    fun location(){
//        LocationManager.init(this,0,object :LocationManager.LocationCallBack{
//            override fun callBack(location: Location?) {
//                Log.d(TAG, "callBack: ${location?.time}")
//            }
//
//            override fun numCall(nums: Int) {
//            }
//
//        })
//    }
//    fun checkPermission() {
//        if(ContextCompat.checkSelfPermission(this,
//                Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
//            ActivityCompat.requestPermissions(this, arrayOf(
//                Manifest.permission.ACCESS_FINE_LOCATION,
//                Manifest.permission.ACCESS_COARSE_LOCATION),10001)
//        }else{
//            location()
//        }
//    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if(requestCode==10001){
//            checkPermission()
//        }
//    }
}

fun MainActivity.getTag(): String {
    return MainActivity::class.java.name
}